package com.originskyseed.platform.count.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.count.mapper.CountVideoEarningsMapper;
import com.originskyseed.platform.count.service.ICountVideoEarningsService;
import com.originskyseed.platform.count.vo.CountVideoEarningsVO;
import com.originskyseed.platform.user.mapper.DeptMapper;
import com.originskyseed.platform.user.mapper.UserInfoMapper;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * Service接口实现类（OSI_ANCHOR_EARNINGS）
 *
 * @author wlj
 */
@DubboService
@Component("countVidoEarningsVOService")
public class CountVideoEarningsServiceImpl implements ICountVideoEarningsService {

	@Resource
	private CountVideoEarningsMapper countVideoEarningsMapper;

	@Resource
	private UserInfoMapper userInfoMapper;

	@Resource
	private DeptMapper deptMapper;

	/**
	 * 收益时间（查询主播流水）查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<CountVideoEarningsVO> selectByTimeEarningsList(Map<String, Object> params, BasePage<CountVideoEarningsVO> page, UserInfo userInfo) throws Exception {
		params.put("page", page);
		params.put("userIdList", deptAnchorIds(userInfo));
		page.setResults(timeEarningsList(params));
		return page;
	}

	/**
	 * 收益时间（查询主播流水）查询列表导出Excel
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<CountVideoEarningsVO> selectByTimeEarningsListToExcel(Map<String, Object> params, UserInfo userInfo) throws Exception {
		params.put("userIdList", deptAnchorIds(userInfo));
		return timeEarningsList(params);
	}

	/**
	 * 主播收益列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<CountVideoEarningsVO> countAnchorEarningsList(Map<String, Object> params, BasePage<CountVideoEarningsVO> page, UserInfo userInfo) throws Exception {
		params.put("page", page);
		page.setResults(anchorEarningsList(params, userInfo));
		return page;
	}

	/**
	 * 主播收益列表导出Excel
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<CountVideoEarningsVO> countAnchorEarningsListToExcel(Map<String, Object> params, UserInfo userInfo) throws Exception {
		return anchorEarningsList(params, userInfo);
	}

	/**
	 * 频道收益列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<CountVideoEarningsVO> countChannelEarningsList(Map<String, Object> params, BasePage<CountVideoEarningsVO> page, UserInfo userInfo) throws Exception {
		params.put("page", page);
		page.setResults(channelEarningsList(params));
		return page;
	}

	/**
	 * 频道收益列表导出Excel
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<CountVideoEarningsVO> countChannelEarningsListToExcel(Map<String, Object> params) throws Exception {
		return channelEarningsList(params);
	}

	/**
	 * 通过主播Id、roomId、直播时间 查询个人/公会开播房间流水
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public String countAnchorEarnins(Map<String, Object> params) throws Exception {
		return this.countVideoEarningsMapper.countAnchorEarnins(params);
	}

	/**
	 * 观看直播用户数
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public int countPlayerViewLivePersons(Map<String, Object> params) throws Exception {
		return this.countPlayerViewLivePersons(params);
	}

	/**
	 * 选择家族下主播列表信息
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<CountVideoEarningsVO> selectAnchorInfoOnFamilyList(Map<String, Object> params) throws Exception {
		return this.countVideoEarningsMapper.selectAnchorInfoOnFamilyList(params);
	}

	/**
	 * 选择家族下频道列表信息
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<CountVideoEarningsVO> selectChannelInfoOnFamilyList(Map<String, Object> params) throws Exception {
		return this.countVideoEarningsMapper.selectChannelInfoOnFamilyList(params);
	}

	/**
	 * 通过主播Id和类型统计主播直播时长
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public int countAnchorLiveTimeByAnchorIdAndType(Map<String, Object> params) throws Exception {
		return this.countVideoEarningsMapper.countAnchorLiveTimeByAnchorIdAndType(params);
	}

	/**
	 * 通过主播Id查询有效天数
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public int countAnchorLiveDayByAnchorId(Map<String, Object> params) throws Exception {
		return this.countVideoEarningsMapper.countAnchorLiveDayByAnchorId(params);
	}

	/**
	 * 通过主播Id查询个人/公会开播房间流水
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public String countAnchorEarninsByAnchorId(Map<String, Object> params) throws Exception {
		return this.countVideoEarningsMapper.countAnchorEarninsByAnchorId(params);
	}

	/**
	 * 时间换算 秒--时分秒
	 * 
	 * @param seconds
	 * @return
	 */
	public String liveTimes(Integer seconds) {
		int temp = 0;
		if(seconds==null)
		{
			return "";
		}
		StringBuffer sb = new StringBuffer();
		temp = seconds / 3600;
		sb.append((temp < 10) ? "" + temp + "小时" : "" + temp + "小时");
		temp = seconds % 3600 / 60;
		sb.append((temp < 10) ? "" + temp + "分" : "" + temp + "分");
		temp = seconds % 3600 % 60;
		sb.append((temp < 10) ? "" + temp + "秒" : "" + temp + "秒");
		return sb.toString();
	}

	/**
	 * 时间收益统计
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public List<CountVideoEarningsVO> timeEarningsList(Map<String, Object> params) throws Exception {
		List<CountVideoEarningsVO> list = this.countVideoEarningsMapper.selectByTimeEarningsList(params);
		for (int i = 0; i < list.size(); i++) {
			CountVideoEarningsVO countVideoEarningsVO = list.get(i);
			params.put("anchorId", countVideoEarningsVO.getAnchorId());
			// 直播有效天数
			int days = this.countVideoEarningsMapper.countAnchorLiveDayByAnchorId(params);
			params.put("type", 1);
			// 个人直播时长
			int personLiveTime = this.countVideoEarningsMapper.countAnchorLiveTimeByAnchorIdAndType(params);
			// 个人房间流水
			String personEarnings = this.countVideoEarningsMapper.countAnchorEarninsByAnchorId(params);
			BigDecimal personAccount = new BigDecimal(personEarnings);
			params.put("type", 2);
			// 排麦直播时长
			int tradeLiveTime = this.countVideoEarningsMapper.countAnchorLiveTimeByAnchorIdAndType(params);
			// 公会房间流水
			String tradeEarnings = this.countVideoEarningsMapper.countAnchorEarninsByAnchorId(params);
			BigDecimal tradeAccount = new BigDecimal(tradeEarnings);
			countVideoEarningsVO.setWorkDay(days);
			countVideoEarningsVO.setPersonLiveTime(liveTimes(personLiveTime));
			if (personAccount.equals(new BigDecimal("0"))) {
				countVideoEarningsVO.setPersonAccount(new BigDecimal(0));
			} else {
				countVideoEarningsVO.setPersonAccount(personAccount.setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			if (tradeAccount.equals(new BigDecimal("0"))) {
				countVideoEarningsVO.setTradeUnionAccount(new BigDecimal(0));
			} else {
				countVideoEarningsVO.setTradeUnionAccount(tradeAccount.setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			countVideoEarningsVO.setTradeUnionLiveTime(liveTimes(tradeLiveTime));
			// 开播总时长
			countVideoEarningsVO.setAllLiveTime(liveTimes(personLiveTime + tradeLiveTime));
			// 家族收益 0对公主播*50% 1对私主播*10%
			BigDecimal account = new BigDecimal((personAccount.add(tradeAccount)).doubleValue());
			// BigDecimal account = personAccount.add(tradeAccount);
			if (account.intValue() != 0) {
				// 主播流水
				countVideoEarningsVO.setAnchorAccount(new BigDecimal(account.doubleValue()).setScale(2, BigDecimal.ROUND_UP));
				if (countVideoEarningsVO.getAnchorSignType() == 0) {
					countVideoEarningsVO.setFamilyEarnings((account.multiply(new BigDecimal("0.5"))).setScale(2, BigDecimal.ROUND_UP));
				}
				if (countVideoEarningsVO.getAnchorSignType() == 1) {
					countVideoEarningsVO.setFamilyEarnings((account.multiply(new BigDecimal("0.1"))).setScale(2, BigDecimal.ROUND_UP));
				}
			} else {
				countVideoEarningsVO.setAnchorAccount(new BigDecimal("0"));
				countVideoEarningsVO.setFamilyEarnings(new BigDecimal("0"));
			}
			list.set(i, countVideoEarningsVO);
		}
		return list;
	}

	/**
	 * 主播收益统计
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public List<CountVideoEarningsVO> anchorEarningsList(Map<String, Object> params, UserInfo userInfo) throws Exception {
		params.put("userIdList", deptAnchorIds(userInfo));
		List<CountVideoEarningsVO> list = this.countVideoEarningsMapper.countAnchorEarningsList(params);
		for (int i = 0; i < list.size(); i++) {
			CountVideoEarningsVO videoEarningsVO = list.get(i);
			if (videoEarningsVO != null) {
				// 直播时长
				videoEarningsVO.setAllLiveTime(liveTimes(videoEarningsVO.getLiveTimeSeconds()));
				// 观看人数
				Map<String, Object> map = new HashMap<>();
				map.put("roomId", videoEarningsVO.getRoomId());
				map.put("anchorId", videoEarningsVO.getAnchorId());
				map.put("startDate", videoEarningsVO.getStartTime());
				map.put("endDate", videoEarningsVO.getEndTime());
				int viewPersons = this.countVideoEarningsMapper.countPlayerViewLivePersons(map);
				map.put("type", 1);
				// 个人房间流水
				String personEarning = this.countVideoEarningsMapper.countAnchorEarnins(map);
				BigDecimal personAccount = new BigDecimal(personEarning);
				// 公会房间流水
				map.put("type", 2);
				String tradeEarning = this.countVideoEarningsMapper.countAnchorEarnins(map);
				BigDecimal tradeAccount = new BigDecimal(tradeEarning);
				BigDecimal account = new BigDecimal((personAccount.add(tradeAccount)).toString());
				// 主播流水
				if (account.intValue() != 0) {
					videoEarningsVO.setAnchorAccount(account.setScale(2, BigDecimal.ROUND_UP));
				} else {
					videoEarningsVO.setAnchorAccount(new BigDecimal("0"));
				}
				// 家族收益 0对公主播*50% 1对私主播*10%
				if (!account.equals(new BigDecimal("0"))) {
					if (videoEarningsVO.getAnchorSignType() == 0) {
						videoEarningsVO.setFamilyEarnings(account.multiply(new BigDecimal("0.5")).setScale(2, BigDecimal.ROUND_UP));
					}
					if (videoEarningsVO.getAnchorSignType() == 1) {
						videoEarningsVO.setFamilyEarnings(account.multiply(new BigDecimal("0.1")).setScale(2, BigDecimal.ROUND_UP));
					}
				} else {
					videoEarningsVO.setFamilyEarnings(new BigDecimal("0"));
				}
				if (!personAccount.equals(new BigDecimal("0"))) {
					videoEarningsVO.setPersonAccount(personAccount.setScale(2, BigDecimal.ROUND_UP));
				} else {
					videoEarningsVO.setPersonAccount(new BigDecimal("0"));
				}
				if (!tradeAccount.equals(new BigDecimal("0"))) {
					videoEarningsVO.setTradeUnionAccount(tradeAccount.setScale(2, BigDecimal.ROUND_UP));
				} else {
					videoEarningsVO.setTradeUnionAccount(new BigDecimal("0"));
				}
				videoEarningsVO.setViewPlayers(viewPersons);
				list.set(i, videoEarningsVO);
			}
		}
		return list;
	}

	/**
	 * 频道收益统计
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public List<CountVideoEarningsVO> channelEarningsList(Map<String, Object> params) throws Exception {
		List<CountVideoEarningsVO> list = this.countVideoEarningsMapper.countChannelEarningsList(params);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (int i = 0; i < list.size(); i++) {
			CountVideoEarningsVO countVideoEarningsVO = list.get(i);
			countVideoEarningsVO.setAllLiveTime(liveTimes(countVideoEarningsVO.getLiveTimeSeconds()));
			// 观看人数
			Map<String, Object> map = new HashMap<>();
			map.put("roomId", countVideoEarningsVO.getRoomId());
			map.put("anchorId", countVideoEarningsVO.getAnchorId());
			map.put("startDate", sdf.format(countVideoEarningsVO.getStartTime()));
			map.put("endDate", sdf.format(countVideoEarningsVO.getEndTime()));
			int viewPersons = this.countVideoEarningsMapper.countPlayerViewLivePersons(map);
			// 公会房间流水
			map.put("type", 2);
			String tradeEarning = this.countVideoEarningsMapper.countAnchorEarnins(map);
			BigDecimal tradeAccount = new BigDecimal(tradeEarning);
			if (tradeAccount.intValue() != 0) {
				countVideoEarningsVO.setTradeUnionAccount(new BigDecimal(tradeAccount.doubleValue()).setScale(2, BigDecimal.ROUND_UP));
			} else {
				countVideoEarningsVO.setTradeUnionAccount(new BigDecimal("0"));
			}
			countVideoEarningsVO.setViewPlayers(viewPersons);
			list.set(i, countVideoEarningsVO);
		}
		return list;
	}

	/**
	 * 查询组织下的部门
	 * 
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		Dept dept = this.deptMapper.selectByCode(code);
		List<Dept> deptList = this.deptMapper.selectByParentCode(code);
		if (deptList != null && deptList.size() > 0) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		} else {
			if (dept != null) {
				list.add(dept.getId());
			}
		}

	}

	/**
	 * 删除重复项
	 * 
	 * @param list
	 * @return
	 */
	private List removeDuplicate(List list) {
		HashSet h = new HashSet(list);
		list.clear();
		list.addAll(h);
		return list;
	}

	/**
	 * 获取家族下的所有主播
	 * 
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	private List<String> deptAnchorIds(UserInfo userInfo) throws Exception {
		Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
		List<String> userIdList = new ArrayList<>();
		if (dept != null) {
			List<String> deptIdList = new ArrayList<>();
			this.selectSonId(dept.getCode(), deptIdList);
			userIdList = this.userInfoMapper.selectAnchorOtherAccountsByDeptIds(removeDuplicate(deptIdList));
		}
		return userIdList;
	}
}
